// main.js
// 模块化函数
function initializeForm() {
    const submitButton = document.getElementById("submitButton");
    const searchKeyword = document.getElementById("searchKeyword");
    const queryResult = document.querySelector(".query .query-result");

    function handleFormSubmit(event) {
        event.preventDefault(); // 阻止表单默认提交行为

        const keyword = searchKeyword.value.trim();

        if (keyword === "") {
            alert("请输入资源检索关键词！");
        } else {
            fetchSearchResults(keyword, queryResult);
        }
    }

    function fetchSearchResults(keyword, resultElement) {
        fetch('hello-servlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'text/plain;charset=UTF-8',  // 设置请求头为纯文本
            },
            body: keyword  // 直接发送纯文本
        })
            .then(response => response.text())
            .then(data => {
                resultElement.textContent = data;
            })
            .catch(error => console.error('Error:', error));
    }

    // 添加事件监听器
    submitButton.addEventListener("click", handleFormSubmit);
}

// 确保DOM完全加载后再初始化表单
document.addEventListener("DOMContentLoaded", initializeForm);